package com.jt.service;

import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class HttpClientServiceImpl implements  HttpClientService{

    //HttpClient测试
    @Override
    public void saveUser(User user) {
        //1.把user转成json
        String json = ObjectMapperUtil.toJson(user);
        //2.动态拼接url
        String url = "http://sso.jt.com/user/httpClient/saveUser?username="
                        +user.getUsername()+"&password="+user.getPassword();
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpClient.execute(get);
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code!=200){
                throw new RuntimeException("服务器异常！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("请求错误，请稍后再试");
        }
    }
}
